using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using QFramework;

public class ToastManager : MonoBehaviour
{
    private static ToastManager instance;
    public static ToastManager Instance
    {
        get
        {
            if (instance == null)
            {
                GameObject go = new GameObject("ToastManager");
                instance = go.AddComponent<ToastManager>();
                DontDestroyOnLoad(go);
            }
            return instance;
        }
    }

    [Header("Toast Settings")]
    public GameObject toastPrefab;        // Toast预制体
    public float showDuration = 2f;       // 显示时长
    public float fadeInDuration = 0.3f;   // 淡入时长
    public float fadeOutDuration = 0.3f;  // 淡出时长
    public Vector2 offset = new Vector2(0, 100f); // 位置偏移

    private GameObject currentToast;      // 当前显示的Toast
    private CanvasGroup canvasGroup;      // 用于控制透明度
    private Text messageText;             // 消息文本组件
    private RectTransform rectTransform;  // 用于控制位置
    private Canvas canvas;                // Canvas组件

    void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
            InitializeToast();
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }
    }

    void Start()
    {
        // 注册关闭Toast的全局事件
        StringEventSystem.Global.Register(EventID.CloseToast, () =>
        {
            CloseToast();
        }).UnRegisterWhenGameObjectDestroyed(gameObject);
    }

    private void InitializeToast()
    {
        Debug.Log("开始初始化Toast...");
        
        if (toastPrefab == null)
        {
            Debug.LogError("Toast prefab is not assigned!");
            return;
        }

        // 确保有Canvas组件
        canvas = GetComponent<Canvas>();
        if (canvas == null)
        {
            Debug.Log("添加Canvas组件...");
            canvas = gameObject.AddComponent<Canvas>();
            canvas.renderMode = RenderMode.ScreenSpaceOverlay;
            canvas.sortingOrder = 9999; // 确保显示在最上层
        }

        // 确保有CanvasScaler组件
        CanvasScaler scaler = GetComponent<CanvasScaler>();
        if (scaler == null)
        {
            Debug.Log("添加CanvasScaler组件...");
            scaler = gameObject.AddComponent<CanvasScaler>();
            scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
            scaler.referenceResolution = new Vector2(1080, 1920);
        }

        // 创建Toast实例
        Debug.Log("创建Toast实例...");
        currentToast = Instantiate(toastPrefab, transform);
        currentToast.SetActive(false);

        // 获取必要组件
        canvasGroup = currentToast.GetComponent<CanvasGroup>();
        if (canvasGroup == null)
        {
            Debug.Log("添加CanvasGroup组件...");
            canvasGroup = currentToast.AddComponent<CanvasGroup>();
        }

        messageText = currentToast.GetComponentInChildren<Text>();
        if (messageText == null)
        {
            Debug.LogError("Toast prefab must have a Text component!");
            return;
        }

        rectTransform = currentToast.GetComponent<RectTransform>();
        if (rectTransform == null)
        {
            Debug.LogError("Toast prefab must have a RectTransform component!");
            return;
        }

        // 设置RectTransform的锚点为屏幕中心
        rectTransform.anchorMin = new Vector2(0.5f, 0.5f);
        rectTransform.anchorMax = new Vector2(0.5f, 0.5f);
        rectTransform.pivot = new Vector2(0.5f, 0.5f);
        rectTransform.anchoredPosition = Vector2.zero; // 初始位置设为锚点位置（屏幕中心）

        Debug.Log("Toast初始化完成！");
    }

    // 显示Toast
    public void ShowToast(string message)
    {
        Debug.Log($"显示Toast: {message}");
        
        if (currentToast == null)
        {
            Debug.LogError("Toast is not initialized!");
            return;
        }

        if (messageText == null)
        {
            Debug.LogError("Message Text component is missing!");
            return;
        }

        // 停止之前的动画
        DOTween.Kill(canvasGroup);
        DOTween.Kill(rectTransform);

        // 设置消息
        messageText.text = message;
        Debug.Log($"设置Toast文本: {message}");

        // 重置状态
        canvasGroup.alpha = 0f;
        currentToast.SetActive(true);
        Debug.Log("Toast已激活");

        // 设置初始位置（屏幕中心偏下）
        rectTransform.anchoredPosition = new Vector2(0, -50f);
        Debug.Log($"设置初始位置: {rectTransform.anchoredPosition}");

        // 创建动画序列
        Sequence sequence = DOTween.Sequence();

        // 淡入动画
        sequence.Append(canvasGroup.DOFade(1f, fadeInDuration));
        sequence.Join(rectTransform.DOAnchorPosY(0f, fadeInDuration).SetEase(Ease.OutBack));

        // 等待显示时间
        sequence.AppendInterval(showDuration);

        // 淡出动画
        sequence.Append(canvasGroup.DOFade(0f, fadeOutDuration));
        sequence.Join(rectTransform.DOAnchorPosY(50f, fadeOutDuration).SetEase(Ease.InBack));

        // 动画完成后隐藏Toast
        sequence.OnComplete(() =>
        {
            currentToast.SetActive(false);
            Debug.Log("Toast动画完成，已隐藏");
        });

        Debug.Log("Toast动画序列已创建");
    }

    // 关闭Toast
    public void CloseToast()
    {
        Debug.Log("关闭Toast");
        if (currentToast == null || !currentToast.activeSelf)
        {
            Debug.Log("Toast未激活或不存在，无需关闭");
            return;
        }

        // 停止所有动画
        DOTween.Kill(canvasGroup);
        DOTween.Kill(rectTransform);

        // 创建关闭动画
        Sequence closeSequence = DOTween.Sequence();
        closeSequence.Append(canvasGroup.DOFade(0f, fadeOutDuration));
        closeSequence.Join(rectTransform.DOAnchorPosY(50f, fadeOutDuration).SetEase(Ease.InBack));
        closeSequence.OnComplete(() =>
        {
            currentToast.SetActive(false);
            Debug.Log("Toast关闭动画完成");
        });
    }

    void OnDestroy()
    {
        // 清理DOTween动画
        DOTween.Kill(canvasGroup);
        DOTween.Kill(rectTransform);
    }
}
